package com.alibaba.citrus.cr.sales.plan.facade.service.salesplan;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanLineQueryService;
import com.alibaba.citrus.cr.sales.plan.api.setting.SalesPlanScItemQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanScItemPageQueryRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanSubTotalRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanLineQueryPortService;
import com.alibaba.citrus.cr.sales.plan.facade.service.statistics.stat.model.PageQueryAddressPortRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.statistics.stat.model.PageQueryProductPlanPortRequest;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanScItemSDO;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.crplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressFilterRequest;
import com.epoch.app.crplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressFilterResponse;
import com.epoch.app.crplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressRequest;
import com.epoch.app.crplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressResponse;
import com.epoch.app.crplatformenhance.opecustomeraddressindex.service.OpeCustomerAddressIndexService;
import com.epoch.app.crplatformenhance.sdo.CustomerAddressSDO;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

/**
 * @author wangyibing
 */
@Component
public class SalesPlanLineQueryPortServiceImpl implements SalesPlanLineQueryPortService {

    private static final Log log = Log.getLogger(SalesPlanLineQueryPortServiceImpl.class);

    @Resource
    private SalesPlanLineQueryService salesPlanLineQueryService;

    @Resource
    private SalesPlanScItemQueryService salesPlanScItemQueryService;

    @Resource
    private OpeCustomerAddressIndexService opeCustomerAddressIndexService;

    @Override
    public Result<PageResult<List<CustomerAddressSDO>>> pageQueryCustomerAddress(PageQueryAddressPortRequest pageQueryAddressPortRequest) {
        //查询客户地址
        PageQueryCustomerAddressRequest request = new PageQueryCustomerAddressRequest();
        pageQueryCustomerAddressConverter(request, pageQueryAddressPortRequest);
        if (StringUtils.isNotBlank(pageQueryAddressPortRequest.getCustomerCode())) {
            request.setCustomerCodeList(Lists.newArrayList(pageQueryAddressPortRequest.getCustomerCode()));
        }
        if (StringUtils.isNotBlank(pageQueryAddressPortRequest.getCustomerName())) {
            request.setCustomerName(pageQueryAddressPortRequest.getCustomerName().trim());
        }
        if (CollectionUtils.isNotEmpty(pageQueryAddressPortRequest.getAddressCodeList())) {
            request.setAddressCodeList(pageQueryAddressPortRequest.getAddressCodeList());
        }
        if (StringUtils.isNotBlank(pageQueryAddressPortRequest.getAddressName())) {
            request.setAddressName(pageQueryAddressPortRequest.getAddressName().trim());
        }
        PageQueryCustomerAddressResponse pageQueryCustomerAddressResponse = opeCustomerAddressIndexService.pageQueryCustomerAddress(request);
        if (pageQueryCustomerAddressResponse.getTotal() == null || pageQueryCustomerAddressResponse.getTotal() == 0) {
            return Result.success(PageResult.of(Lists.newArrayList(), 0));
        }
        List<CustomerAddressSDO> collect = pageQueryCustomerAddressResponse.getResult().stream().map(index -> {
            CustomerAddressSDO customerAddress = new CustomerAddressSDO();
            BeanUtils.copyProperties(index, customerAddress);
            customerAddress.setId(Objects.toString(index.getId()));
            return customerAddress;
        }).collect(Collectors.toList());
        return Result.success(PageResult.of(collect, pageQueryCustomerAddressResponse.getTotal()));
    }

    private void pageQueryCustomerAddressConverter(PageQueryCustomerAddressRequest request, PageQueryAddressPortRequest pageQueryAddressPortRequest) {
        if (pageQueryAddressPortRequest.getBizType() == null && StringUtil.isBlank(pageQueryAddressPortRequest.getBizId())) {
            throw new FacadeException("OTS-02-002-02-15-007");
        }
        //业务单元以上的能查看所有数据
        if (pageQueryAddressPortRequest.getBizType() >= SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType()) {
            SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(pageQueryAddressPortRequest.getBizType());
            if (byOrganizationType == null) {
                throw new FacadeException("OTS-02-002-02-15-007");
            }
            switch (byOrganizationType) {
                case SALESMAN:
                    request.setPrincipal(pageQueryAddressPortRequest.getBizId());
                    break;
                case SALES_DEPARTMENT:
                    request.setOrgSaleDepartmentCodeList(Lists.newArrayList(pageQueryAddressPortRequest.getBizId()));
                    break;
                case SALES_CHANNEL:
                    request.setOrgSaleChannelCodeList(Lists.newArrayList(pageQueryAddressPortRequest.getBizId()));
                    break;
                case SALES_ORGANIZATION:
                    request.setOrgSaleOrganizationCodeList(Lists.newArrayList(pageQueryAddressPortRequest.getBizId()));
                    break;
                case BUSINESS_UNIT:
                    request.setOrgBussinessUnitCodeList(Lists.newArrayList(pageQueryAddressPortRequest.getBizId()));
                    break;
                default:
            }
        }
        //查询启用数据
        request.setStatus(1);
        request.setStart(pageQueryAddressPortRequest.getStart());
        request.setLimit(pageQueryAddressPortRequest.getLimit());
    }

    @Override
    public Result<PageResult<List<SalesPlanScItemSDO>>> pageQueryProductPlan(PageQueryProductPlanPortRequest pageQueryProductPlanPortRequest) {
        SalesPlanScItemPageQueryRequest salesPlanScItemPageQueryRequest = new SalesPlanScItemPageQueryRequest();
        //计划明细添加计划货品拿业务渠道获取(计划货品范围优化版本改动)
        //salesPlanScItemPageQueryRequest.setOrgSalesChannelCode(pageQueryProductPlanPortRequest.getOrgSalesChannelCode());
        salesPlanScItemPageQueryRequest.setOrgBusinessChannelCode(pageQueryProductPlanPortRequest.getOrgBusinessChannelCode());
        salesPlanScItemPageQueryRequest.setOrgSalesOrganizationCode(pageQueryProductPlanPortRequest.getOrgSalesOrganizationCode());
        salesPlanScItemPageQueryRequest.setScItemId(pageQueryProductPlanPortRequest.getScItemId());
        //查询启用数据
        salesPlanScItemPageQueryRequest.setStatus(1);
        if (Strings.isNotBlank(pageQueryProductPlanPortRequest.getScItemName())) {
            salesPlanScItemPageQueryRequest.setScItemName(pageQueryProductPlanPortRequest.getScItemName().trim());
        }
        salesPlanScItemPageQueryRequest.setPage(pageQueryProductPlanPortRequest.getPage());
        salesPlanScItemPageQueryRequest.setSize(pageQueryProductPlanPortRequest.getSize());
        salesPlanScItemPageQueryRequest.setOuterId(pageQueryProductPlanPortRequest.getOuterId());
        Result<PageResult<List<SalesPlanScItemSDO>>> pageResultResult = salesPlanScItemQueryService.pageQueryProductPlanList(salesPlanScItemPageQueryRequest);
        if (null == pageResultResult || null == pageResultResult.getResult() || CollectionUtils.isEmpty(pageResultResult.getResult().getContent())){
            log.warn("SalesPlanLineQueryPortServiceImpl.pageQueryProductPlan ProductPlanList is null");
            return Result.success(new PageResult<>(Lists.newArrayList(),0));
        }
        //构造查询计划明细条件
        SalesPlanSubTotalRequest salesPlanSubTotalRequest = new SalesPlanSubTotalRequest();
        salesPlanSubTotalRequestConverter(salesPlanSubTotalRequest, pageQueryProductPlanPortRequest);
        Result<List<String>> listResult = salesPlanLineQueryService.querySalesPlanLineByScItem(salesPlanSubTotalRequest);
        List<SalesPlanScItemSDO> collect = pageResultResult.getResult().getContent().stream().map(salesPlanScItemSDO -> {
            if (!listResult.getResult().contains(salesPlanScItemSDO.getScItemId())) {
                salesPlanScItemSDO.setIsDisable(false);
            } else {
                salesPlanScItemSDO.setIsDisable(true);
            }
            SalesPlanScItemSDO salesPlanScItemSDO1 = new SalesPlanScItemSDO();
            BeanUtils.copyProperties(salesPlanScItemSDO, salesPlanScItemSDO1);
            return salesPlanScItemSDO1;
        }).collect(Collectors.toList());
        return Result.success(PageResult.of(collect, pageResultResult.getResult().getTotalElements()));
    }

    @Override
    public Result<PageResult<List<CustomerAddressSDO>>> pageQueryCustomerAddressFilter(PageQueryAddressPortRequest pageQueryAddressPortRequest) {
        //查询客户地址
        PageQueryCustomerAddressFilterRequest request = new PageQueryCustomerAddressFilterRequest();
        pageQueryCustomerAddressConverter(request, pageQueryAddressPortRequest);
        if (StringUtils.isNotBlank(pageQueryAddressPortRequest.getCustomerCode())) {
            request.setCustomerCodeList(Lists.newArrayList(pageQueryAddressPortRequest.getCustomerCode()));
        }
        if (StringUtils.isNotBlank(pageQueryAddressPortRequest.getCustomerName())) {
            request.setCustomerName(pageQueryAddressPortRequest.getCustomerName().trim());
        }
        if (CollectionUtils.isNotEmpty(pageQueryAddressPortRequest.getAddressCodeList())) {
            request.setAddressCodeList(pageQueryAddressPortRequest.getAddressCodeList());
        }
        if (StringUtils.isNotBlank(pageQueryAddressPortRequest.getAddressName())) {
            request.setAddressName(pageQueryAddressPortRequest.getAddressName().trim());
        }
        PageQueryCustomerAddressFilterResponse pageQueryCustomerAddressResponse = opeCustomerAddressIndexService.pageQueryCustomerAddressFilter(request);
        if (pageQueryCustomerAddressResponse.getTotal() == null || pageQueryCustomerAddressResponse.getTotal() == 0) {
            return Result.success(PageResult.of(Lists.newArrayList(), 0));
        }
        List<CustomerAddressSDO> collect = pageQueryCustomerAddressResponse.getResult().stream().map(index -> {
            CustomerAddressSDO customerAddress = new CustomerAddressSDO();
            BeanUtils.copyProperties(index, customerAddress);
            customerAddress.setId(Objects.toString(index.getId()));
            return customerAddress;
        }).collect(Collectors.toList());
        return Result.success(PageResult.of(collect, pageQueryCustomerAddressResponse.getTotal()));
    }

    private void pageQueryCustomerAddressConverter(PageQueryCustomerAddressFilterRequest request, PageQueryAddressPortRequest pageQueryAddressPortRequest) {
        if (pageQueryAddressPortRequest.getBizType() == null && StringUtil.isBlank(pageQueryAddressPortRequest.getBizId())) {
            throw new FacadeException("OTS-02-002-02-15-007");
        }
        //业务单元以上的能查看所有数据
        if (pageQueryAddressPortRequest.getBizType() >= SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType()) {
            SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(pageQueryAddressPortRequest.getBizType());
            if (byOrganizationType == null) {
                throw new FacadeException("OTS-02-002-02-15-007");
            }
            switch (byOrganizationType) {
                case SALESMAN:
                    request.setPrincipal(pageQueryAddressPortRequest.getBizId());
                    break;
                case SALES_DEPARTMENT:
                    request.setOrgSaleDepartmentCodeList(Lists.newArrayList(pageQueryAddressPortRequest.getBizId()));
                    break;
                case SALES_CHANNEL:
                    request.setOrgSaleChannelCodeList(Lists.newArrayList(pageQueryAddressPortRequest.getBizId()));
                    break;
                case SALES_ORGANIZATION:
                    request.setOrgSaleOrganizationCodeList(Lists.newArrayList(pageQueryAddressPortRequest.getBizId()));
                    break;
                case BUSINESS_UNIT:
                    request.setOrgBussinessUnitCodeList(Lists.newArrayList(pageQueryAddressPortRequest.getBizId()));
                    break;
                default:
            }
        }
        //查询启用数据
        request.setStatus(1);
        request.setStart(pageQueryAddressPortRequest.getStart());
        request.setLimit(pageQueryAddressPortRequest.getLimit());
    }

    private void salesPlanSubTotalRequestConverter(SalesPlanSubTotalRequest salesPlanSubTotalRequest, PageQueryProductPlanPortRequest pageQueryProductPlanPortRequest) {
        if (StringUtils.isNotBlank(pageQueryProductPlanPortRequest.getPlanId())) {
            salesPlanSubTotalRequest.setPlanId(Long.parseLong(pageQueryProductPlanPortRequest.getPlanId()));
        }
        if (StringUtils.isNotEmpty(pageQueryProductPlanPortRequest.getAddressCode())) {
            salesPlanSubTotalRequest.setCustomerAddress(pageQueryProductPlanPortRequest.getAddressCode());
        }
        if (StringUtils.isNotBlank(pageQueryProductPlanPortRequest.getAddressId())){
            salesPlanSubTotalRequest.setCustomerAddressId(pageQueryProductPlanPortRequest.getAddressId());
        }
    }

}
